package com.cqrcb.cloud.config.dubbo;

import com.cqrcb.cloud.config.utils.DubboConstants;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.*;
import org.slf4j.MDC;

import java.util.UUID;

/**
 * @author lpe234
 * @since 2019/5/25 15:24
 */
public class DubboTraceIdFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        String mdcTraceId = MDC.get(DubboConstants.TRACE_ID);
        String traceId = RpcContext.getContext().getAttachment(DubboConstants.TRACE_ID);
        if (StringUtils.isBlank(mdcTraceId) && StringUtils.isBlank(traceId)) {
            traceId = this.getUUID();
        }else if(StringUtils.isBlank(traceId)) {
            traceId = mdcTraceId;
        }

        Object[] arguments = invocation.getArguments();
        //设置日志traceId变量
        MDC.put(DubboConstants.TRACE_ID, traceId);
        RpcContext.getContext().setAttachment(DubboConstants.TRACE_ID, traceId);
        Result result = invoker.invoke(invocation);
//        RpcContext.getContext().remove(DubboConstants.TRACE_ID);
//        MDC.remove(DubboConstants.TRACE_ID);
        return result;
    }

    /**
     * 获取UUID
     *
     * @return String UUID
     */
    public String getUUID() {
        String uuid = UUID.randomUUID().toString();
        //替换-字符
        return uuid.replaceAll("-", "");
    }

}
